const users = [
  { id: 1, name: "胖卡", city: "桂林" },
  { id: 2, name: "Tom", city: "北京" },
  { id: 3, name: "Jonny", city: "深圳" },
];

const getAllUsers = (req, res) => {
  res.writeHead(200, {
    "Content-Type": "application/json",
  });
  res.end(JSON.stringify(users));
};

const getUserHandler = (req, res) => {
  const id = req.url.split("/")[3];
  const user = users.find((user) => user.id === parseInt(id));
  console.log(user);
  res.setHeader("content-type", "application/json");
  if (user) {
    res.statusCode = 200;
    res.end(JSON.stringify(user));
  } else {
    res.statusCode = 404;
    res.end(JSON.stringify({ message: `No User for id ${id}` }));
  }
};

const createUserHandler = (req, res) => {
  let body = "";
  // listen body
  req.on("data", (chunk) => (body += chunk));
  req.on("end", () => {
    const newUser = JSON.parse(body);
    users.push(newUser);
    res.end(
      JSON.stringify({
        message: "Add User Success.",
      })
    );
  });
};

export {createUserHandler, getUserHandler,getAllUsers };
